import { Tile as TileLayer } from 'ol/layer'
import { TIANDI_KEY } from '../constant'
import { get } from 'ol/proj';
import { getWidth, getTopLeft } from 'ol/extent'
import { WMTS } from 'ol/source'
import WMTSTileGrid from 'ol/tilegrid/WMTS'
import { TiandiTileLayerConfigEnum } from '@/enum'

export const projection = get("EPSG:4326")!;
const projectionExtent = projection.getExtent();
const size = getWidth(projectionExtent) / 256;
const resolutions: Array<number> = [];
for (let z = 2; z < 19; ++z) {
  resolutions[z] = size / Math.pow(2, z);
}

// 加载天地图
export function useTianTileLayer(layerType: TiandiTileLayerConfigEnum) {
  const map: {[k: string]: any} = {
    0: ['vec', 'cva'], // [矢量底图, 矢量注记]
    1: ['img', 'cia'], // [影像底图, 影像注记]
    2: ['ter', 'cta']  // [地形晕渲, 地形注记]
  }

  // c: 经纬度投影 w: 球面墨卡托投影
  const matrixSet = 'c'

  return [
    // 底图
    new TileLayer({
      source: new WMTS({
        url: `http://t{0-6}.tianditu.com/${map[layerType][0]}_${matrixSet}/wmts?tk=${TIANDI_KEY}`,
        layer: map[layerType][0],
        matrixSet: matrixSet,
        style: "default",
        crossOrigin: 'anonymous', // 如果不设置crossOrigin为anonymous 将无法将地图导出为图片 如无该需求可不添加
        format: "tiles",
        wrapX: true,
        tileGrid: new WMTSTileGrid({
          origin: getTopLeft(projectionExtent),
          //resolutions: res.slice(0, 15),
          resolutions: resolutions,
          matrixIds: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14']
        })
      })
    }),
    // 标注
    new TileLayer({
      source: new WMTS({
        url: `http://t{0-6}.tianditu.com/${map[layerType][1]}_${matrixSet}/wmts?tk=${TIANDI_KEY}`,
        layer: map[layerType][1],
        matrixSet: matrixSet,
        style: "default",
        crossOrigin: 'anonymous', // 如果不设置crossOrigin为anonymous 将无法将地图导出为图片 如无该需求可不添加
        format: "tiles",
        wrapX: true,
        tileGrid: new WMTSTileGrid({
          origin: getTopLeft(projectionExtent),
          resolutions: resolutions,
          matrixIds: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14']
        })
      })
    })
  ]
}